package com.zhonghui.dolo.manager.dao.impl;

import com.zhonghui.dolo.manager.dao.GoodsDao;
import com.zhonghui.dolo.manager.dao.mapper.GoodsMapper;
import com.zhonghui.dolo.manager.model.Goods;
import com.zhonghui.dolo.manager.model.GoodsExample;
import com.zhonghui.dolo.manager.model.vo.GoodsReqVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

@Repository
public class GoodsDaoImpl implements GoodsDao {

    @Autowired
    private GoodsMapper goodsMapper;

    @Override
    public List<Goods> queryGoodsList() {
        GoodsExample goodsExample = new GoodsExample();
        return goodsMapper.selectByExample(goodsExample);
    }

    @Override
    public List<Goods> queryGoodsListByGoodsName(String goodsName) {
        GoodsExample goodsExample = new GoodsExample();
        GoodsExample.Criteria criteria = goodsExample.createCriteria();
        if (!StringUtils.isEmpty(goodsName)) {
            criteria.andGoodsNameLike(goodsName +"%");
        }
        return goodsMapper.selectByExample(goodsExample);
    }

    @Override
    public List<Goods> queryGoodsListByParam(GoodsReqVo goodsReqVo) {
        GoodsExample goodsExample = new GoodsExample();
        GoodsExample.Criteria criteria = goodsExample.createCriteria();
        if (!StringUtils.isEmpty(goodsReqVo.getGoodsName())) {
            criteria.andGoodsNameLike(goodsReqVo.getGoodsName() +"%");
        }
        if (goodsReqVo.getIsMarketable() != null) {
            criteria.andIsMarketableEqualTo(goodsReqVo.getIsMarketable().byteValue());
        }
        if (goodsReqVo.getCreateTimeBegin() != null) {
            criteria.andCreateTimeGreaterThanOrEqualTo(new Date(goodsReqVo.getCreateTimeBegin()));
        }
        if (goodsReqVo.getCreateTimeEnd() != null) {
            criteria.andCreateTimeLessThanOrEqualTo(new Date(goodsReqVo.getCreateTimeEnd()));
        }
        goodsExample.setOrderByClause("goods_id desc");
        return goodsMapper.selectByExample(goodsExample);
    }

    @Override
    public Goods getGoodsById(Integer goodsId, Boolean isIncludeDetail) {
        if (Boolean.TRUE.equals(isIncludeDetail)) {
            GoodsExample example = new GoodsExample();
            example.createCriteria().andGoodsIdEqualTo(goodsId);

            List<Goods> goodsList = goodsMapper.selectByExampleWithBLOBs(example);
            if (goodsList.size() == 0) {
                return null;
            }
            return goodsList.get(0);
        }
        return goodsMapper.selectByPrimaryKey(goodsId);
    }

    @Override
    public int updateByGoodsId(Goods goods) {
        return goodsMapper.updateByPrimaryKeySelective(goods);
    }

    @Override
    public int addGoods(Goods goods) {
        return goodsMapper.insertSelective(goods);
    }
}
